﻿
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;

namespace efuture.xml
{
    public interface IControlIterator
    {
        void handle(Control c);
    }

    public class XMLHelper
    {
        public static void GetControls(Control _Control, IControlIterator i)
        {
            Stack<Control> stk = new Stack<Control>();
            stk.Push(_Control);

            while (stk.Count > 0)
            {
                Control c = stk.Pop();

                i.handle(c);

                if (c.HasChildren)
                {

                    foreach (Control _c in c.Controls)
                    {
                        stk.Push(_c);
                    }
                }
            }
        }

        public static bool ShowException(String xmlData, bool ifShow)
        {
            if (String.IsNullOrEmpty(xmlData))
            {
                MessageBox.Show("xmlData is null");
                return true;
            }

            XPathDocument _xDoc = new XPathDocument(new StringReader(xmlData));
            XPathNavigator _xNav = _xDoc.CreateNavigator();

            XPathNavigator errMsg = _xNav.SelectSingleNode("/Root/Exception/ErrorMessage");
            if (errMsg != null)
            {
                if (ifShow)
                {
                    MessageBox.Show(errMsg.Value);
                }
                return true;
            }

            return false;
        }

        public static String SetXml(String xmlData)
        {
            return "<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>" + xmlData + "</Root>";
        }

        public static XPathNavigator CreateNavigator(String xmlData)
        {
            return CreateNavigator(new StringReader(xmlData));
        }

        public static XPathNavigator CreateNavigator(StringReader reader)
        {
            return new XPathDocument(reader).CreateNavigator();
        }

        public static XPathNavigator CreateNavigator(XmlReader reader)
        {
            return new XPathDocument(reader).CreateNavigator();
        }

        public static String SelectSingleValue(String xmlData, String xpath)
        {
            String v = String.Empty;
            try
            {
                XPathNavigator node = CreateNavigator(xmlData).SelectSingleNode(xpath);

                v = (node == null) ? String.Empty : node.Value;
            }
            catch (Exception e)
            {
                MessageBox.Show("err " + e.Message);
            }
            return v;
        }
    }
}
